// const url_all = {
// 	'DEV': 'http://store.test', // 开发
// 	'PRO': 'http://111.111.111.111:8080', // 生产
// }
// let BASEURL = url_all['DEV'] // 调整当前环境
/*
 * 全局请求封装
 * @param url 请求路径
 * @param method 请求类型(GET/POST/DELETE等)
 * @oaram data 请求体数据
 */
import {baseUrl} from './config.js' 

// const refreshTokenPromise = null; // 用于保存刷新token的Promise

export default (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Authorization': 'Bearer ' + uni.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.success !== true && res.statusCode != 401) {
          return uni.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
        } else if (res.data.success !== true && res.statusCode === 401) {
			
          refreshToken().then(() => {
            // 刷新成功后重新发起原始请求
            return uni.request({
              url: baseUrl + options.url,
              method: options.method || 'GET',
              data: options.data || {},
              header: {
                'Authorization': 'Bearer ' + uni.getStorageSync('token')
              }
            });
          }).then(res => {
            if (res.data.success !== true) {
              return uni.showToast({
                title: '获取数据失败',
                icon: 'none'
              });
            }
            resolve(res.data);
          }).catch(err => {
            reject(err);
          });
        } else {
          resolve(res.data);  
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

// 刷新 Token 的函数
function refreshToken() {
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + '/api/v1/authorizations/current',
      method: 'PUT',
      header: {
        'Authorization': 'Bearer ' + uni.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.success) {
		  uni.removeStorageSync('token');
          const newToken = res.data.data.original.access_token;
          uni.setStorageSync('token', newToken);
          resolve();
        } else {
          reject(new Error('刷新 token 失败'));
		  uni.removeStorageSync('token');
		  uni.removeStorageSync('userInfo');
        }
      },
      fail: (err) => {
		uni.removeStorageSync('token');
		uni.removeStorageSync('userInfo');
        reject(err);
      }
    });
  });
}